﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace OnlineCourse.JWTAuthorizePolicy
{
    public class JwtToken
    {
        /// <summary>
        /// 获取基于JWT的Token
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static dynamic BuildJwtToken(Claim[] claims, PermissionRequirement permissionRequirement)//构建Jwt令牌，许可的要求
        {
            var now = DateTime.UtcNow;//世界时间
            var jwt = new JwtSecurityToken(   //Jwt安全令牌
                issuer: permissionRequirement.Issuer,//发行人
                audience: permissionRequirement.Audience,//订阅人
                claims: claims,//要求，请求权
                notBefore: now,
                expires: now.Add(permissionRequirement.Expiration),//有效期，添加许可要求的有效期
                signingCredentials: permissionRequirement.SigningCredentials//签名证书：许可要求的签名证书
            );
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);//Jwt编码，Jwt安全令牌，书写令牌
            var responseJson = new
            {
                Status = true,//重要身份
                access_token = encodedJwt,//访问令牌
                expires_in = permissionRequirement.Expiration.TotalMilliseconds,//到期时间，毫秒
                token_type = "Bearer"//令牌类型
            };
            return responseJson;
        }
    }
}
